package com.ynet.middleground.contract.model;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ynet.core.common.PagerInfo;
import com.ynet.core.exception.BusinessException;
import com.ynet.middleground.contract.bean.*;
import com.ynet.middleground.contract.constant.OperationTypeEnum;
import com.ynet.middleground.contract.constant.SystemConsts;
import com.ynet.middleground.contract.constant.TemplateConsts;
import com.ynet.middleground.contract.dao.*;
import com.ynet.middleground.contract.dto.*;
import com.ynet.middleground.contract.entity.*;
import com.ynet.middleground.contract.utils.CommUtils;
import com.ynet.middleground.contract.utils.GeneralService;
import com.ynet.middleground.user.dto.UserInfoDto;
import org.apache.commons.lang3.StringUtils;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class PortAdminWebModel extends ServiceImpl<TemplateMapper, Template> {

    /**
     * 合同模板表dao
     */
    @Autowired
    TemplateMapper templateMapper;

    /**
     * 根据对象的属性复制到另一对象上的同名属性值
     */
    @Autowired
    Mapper dozerBeanMapper;

    /**
     * 用户中心服务调用模块
     */
    @Autowired
    UserCenterModel userCenterModel;

    /**
     * 合约模板服务统计表dao
     */
    @Autowired
    TemplateOperationLogMapper templateOperationLogMapper;

    /**
     * 档案统计表dao
     */
    @Autowired
    ArchiveOperationLogMapper archiveOperationLogMapper;

    /**
     * 合约主表dao
     */
    @Autowired
    ContractMapper contractMapper;

    /**
     * 档案列表dao
     */
    @Autowired
    ArchiveMapper archiveMapper;

    /**
     * 服务统计表dao
     */
    @Autowired
    ServiceRecordMapper serviceRecordMapper;

    /**
     * 通用服务类，不存放静态方法
     */
    @Autowired
    GeneralService generalService;

    /**
     * 合约类型业务处理类
     */
    @Autowired
    private ContractTypeModel contractTypeModel;
    
    /**
     * 通用工具类
     */
    @Autowired
    CommUtils commUtils;

    /**
     * 根据查询条件分页查询合约模板列表
     *
     * @param requestObj 分页查询模板信息请求信息
     * @return 合约模板列表
     */
    public List<PortTemplateDTO> listTemplates(PortQueryTemplateReqPager requestObj) {

        String channel = requestObj.getChannel();

        checkChannel(channel);

        String createTimeStart = requestObj.getCreateTimeStart();
        String createTimeEnd = requestObj.getCreateTimeEnd();
        String activeTimeStart = requestObj.getActiveTimeStart();
        String activeTimeEnd = requestObj.getActiveTimeEnd();

        String queryChannel = requestObj.getQueryChannel();
        String productType = requestObj.getProductType();
        String name = requestObj.getName();
        String type = requestObj.getType();
        String status = requestObj.getStatus();
        Integer contractTypeId = requestObj.getContractTypeId();
        PagerInfo pagerInfo = requestObj.getPagerInfo();

        Page<Template> templatePage = new Page<>(pagerInfo.getPageNum(), pagerInfo.getPageSize());

        // 参数
        QueryWrapper<Template> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("is_deleted", "0");

        if (StringUtils.isNotEmpty(productType)) {
            queryWrapper.like("product_type", productType);
        }

        if (StringUtils.isNotEmpty(name)) {
            queryWrapper.like("name", name);
        }

        if (StringUtils.isNotEmpty(type)) {
            queryWrapper.eq("type", type);
        }

        if (StringUtils.isNotEmpty(status)) {
            queryWrapper.eq("status", status);
        }
        if (StringUtils.isNotEmpty(queryChannel)) {
            queryWrapper.eq("channel", queryChannel);
        }

        if (contractTypeId != null) {
            queryWrapper.eq("contract_type_id", contractTypeId);
        }

        if (StringUtils.isNotEmpty(createTimeStart) && StringUtils.isNotEmpty(createTimeEnd)) {
            // 创建时间
            queryWrapper.between("gmt_create", createTimeStart + " 00:00:00", createTimeEnd + " 23:59:59");
        } else {
            if (StringUtils.isNotEmpty(createTimeStart)) {
                queryWrapper.ge("gmt_create", createTimeStart + " 00:00:00");
            } else if (StringUtils.isNotEmpty(createTimeEnd)) {
                queryWrapper.le("gmt_create", createTimeEnd + " 23:59:59");
            }
        }

        if (StringUtils.isNotEmpty(activeTimeStart) && StringUtils.isNotEmpty(activeTimeEnd)) {
            // 启动时间
            queryWrapper.between("gmt_active", activeTimeStart + " 00:00:00", activeTimeEnd + " 23:59:59");
        } else {
            if (StringUtils.isNotEmpty(activeTimeStart)) {
                queryWrapper.ge("gmt_active", activeTimeStart + " 00:00:00");
            } else if (StringUtils.isNotEmpty(activeTimeEnd)) {
                queryWrapper.le("gmt_active", activeTimeEnd + " 23:59:59");
            }
        }
        queryWrapper.orderByDesc("gmt_create");
        // 查询合约
        IPage<Template> templateIPage = this.templateMapper.selectPage(templatePage, queryWrapper);

        List<PortTemplateDTO> portTemplateDtos = new ArrayList<>();

        List<Template> records = templateIPage.getRecords();
        if (templateIPage.getRecords() != null) {
            records.forEach(template -> {
                PortTemplateDTO portTemplateDTO = dozerBeanMapper.map(template, PortTemplateDTO.class);
                ContractType contractType = contractTypeMapper.selectById(template.getContractTypeId());
                if (contractType != null) {
                    portTemplateDTO.setContractType(contractType.getName());
                } else {
                    portTemplateDTO.setContractType("");
                }

                portTemplateDTO.setGmtCreate(generalService.localDateTime2Date(template.getGmtCreate()));
                if (template.getGmtActive() != null) {
                    portTemplateDTO.setGmtActive(generalService.localDateTime2Date(template.getGmtActive()));
                }

                if (template.getGmtInactive() != null) {
                    portTemplateDTO.setGmtInactive(generalService.localDateTime2Date(template.getGmtInactive()));
                }

                portTemplateDTO.setGmtModified(generalService.localDateTime2Date(template.getGmtModified()));
                if (template.getContent() != null) {
                    portTemplateDTO.setContent(commUtils.getOssFullUrl(template.getContent()));
                }
                portTemplateDtos.add(portTemplateDTO);
            });
        }
        pagerInfo.setTotal(templateIPage.getTotal());

        return portTemplateDtos;
    }

    /**
     * 内管模版日志查询
     *
     * @param requestObj 内管模版日志查询
     * @return 提供给内管使用的模板日志传输对象
     */
    public List<PortTemplateLogDTO> portTemplateLog(PortTemplateLogQueryReq requestObj) {
        String channel = requestObj.getChannel();
        checkChannel(channel);
        PagerInfo pagerInfo = requestObj.getPagerInfo();
        Page<TemplateOperationLog> archiveLogPage = new Page<>(pagerInfo.getPageNum(), pagerInfo.getPageSize());
        QueryWrapper<TemplateOperationLog> queryWrapper = new QueryWrapper<>();
        String operationName = requestObj.getOperationName();
        String queryChannel = requestObj.getQueryChannel();
        String operationType = requestObj.getOperationType();
        String operationAccount = requestObj.getOperationAccount();
        String endDate = requestObj.getOperationEndDate();
        String begintDate = requestObj.getOperationStartDate();
        List<PortTemplateLogDTO> responseList = new ArrayList<>();

        if (StringUtils.isNotEmpty(queryChannel)) {
            queryWrapper.eq("channel", queryChannel);
        }

        if (StringUtils.isNotEmpty(operationName)) {
            queryWrapper.like("operator_name", operationName);
        }

        if (StringUtils.isNotEmpty(operationAccount)) {
            queryWrapper.like("operator_account", operationAccount);
        }

        if (StringUtils.isNotEmpty(operationType)) {
            queryWrapper.eq("operation_type", operationType);
        }

        if (StringUtils.isNotEmpty(begintDate) && StringUtils.isNotEmpty(endDate)) {
            // 创建时间
            queryWrapper.between("gmt_create", begintDate + " 00:00:00", endDate + " 23:59:59");
        } else {
            if (StringUtils.isNotEmpty(begintDate)) {
                queryWrapper.ge("gmt_create", begintDate + " 00:00:00");
            } else if (StringUtils.isNotEmpty(endDate)) {
                queryWrapper.le("gmt_create", endDate + " 23:59:59");
            }
        }
        queryWrapper.orderByDesc("gmt_create");
        // 查询
        IPage<TemplateOperationLog> archiveOperationLogIPage =
            templateOperationLogMapper.selectPage(archiveLogPage, queryWrapper);

        List<TemplateOperationLog> records = archiveOperationLogIPage.getRecords();
        if (records != null) {
            records.forEach(value -> {
                PortTemplateLogDTO item = dozerBeanMapper.map(value, PortTemplateLogDTO.class);
                item.setGmtCreate(generalService.localDateTime2Date(value.getGmtCreate()));
                item.setGmtModified(generalService.localDateTime2Date(value.getGmtModified()));
                responseList.add(item);
            });
        }
        pagerInfo.setTotal(archiveOperationLogIPage.getTotal());
        return responseList;
    }

    /**
     * 内管模版统计查询查询
     *
     * @param requestObj 内管模版统计查询查询
     * @return 内管使用的模板统计信息传输对象
     */
    public List<PortTemplateTypeStatisticalDTO> portTemplateTypeStatistical(PortTemplateTypeStatisticalReq requestObj) {
        // 参数
        QueryWrapper<TemplateOperationLog> queryWrapper = new QueryWrapper<>();
        String channel = requestObj.getChannel();
        PagerInfo pagerInfo = requestObj.getPagerInfo();
        Page<TemplateOperationLog> templatePage = new Page<>(pagerInfo.getPageNum(), pagerInfo.getPageSize());

        checkChannel(channel);
        String queryChannel = requestObj.getQueryChannel();
        String templateType = requestObj.getTemplateType();
        String begintDate = requestObj.getBegintDate();
        String endDate = requestObj.getEndDate();

        if (StringUtils.isNotEmpty(begintDate) && StringUtils.isNotEmpty(endDate)) {
            // 创建时间
            queryWrapper.between("gmt_create", begintDate + " 00:00:00", endDate + " 23:59:59");
        } else {
            if (StringUtils.isNotEmpty(begintDate)) {
                queryWrapper.ge("gmt_create", begintDate + " 00:00:00");
            } else if (StringUtils.isNotEmpty(endDate)) {
                queryWrapper.le("gmt_create", endDate + " 23:59:59");
            }
        }

        if (StringUtils.isNotEmpty(queryChannel)) {
            queryWrapper.eq("channel", queryChannel);
        }

        // 模版类型
        if (StringUtils.isNotEmpty(templateType)) {
            queryWrapper.eq("template_type", templateType);
        }

        // 统计数量 begin

        // 操作方式
        String invoke = String.valueOf(OperationTypeEnum.INVOKE.getCode());
        queryWrapper.eq("operation_type", invoke);
        // 合约模版类型
        String contractType = TemplateConsts.TPL_TYPE_CONTRACT;
        String archiveType = TemplateConsts.TPL_TYPE_ARCHIVE;
        String agreementType = TemplateConsts.TPL_TYPE_AGREEMENT;
        Integer c01ContractTypeCount = archiveOperationLogMapper.statisticalNumber(contractType, invoke, "C01");
        Integer c02ContractTypeCount = archiveOperationLogMapper.statisticalNumber(contractType, invoke, "C02");
        Integer c03ContractTypeCount = archiveOperationLogMapper.statisticalNumber(contractType, invoke, "C03");

        Integer c01ArchiveTypeCount = archiveOperationLogMapper.statisticalNumber(archiveType, invoke, "C01");
        Integer c02ArchiveTypeCount = archiveOperationLogMapper.statisticalNumber(archiveType, invoke, "C02");
        Integer c03ArchiveTypeCount = archiveOperationLogMapper.statisticalNumber(archiveType, invoke, "C03");

        Integer c01AgreementTypeCount = archiveOperationLogMapper.statisticalNumber(agreementType, invoke, "C01");
        Integer c02AgreementTypeCount = archiveOperationLogMapper.statisticalNumber(agreementType, invoke, "C02");
        Integer c03AgreementTypeCount = archiveOperationLogMapper.statisticalNumber(agreementType, invoke, "C03");
        // 统计数量 end

        queryWrapper.orderByDesc("gmt_create");
        // 查询
        IPage<TemplateOperationLog> templateIPage = templateOperationLogMapper.selectPage(templatePage, queryWrapper);

        List<PortTemplateTypeStatisticalDTO> portTemplateLogDtos = new ArrayList<>();

        List<TemplateOperationLog> records = templateIPage.getRecords();
        if (records != null) {
            records.forEach(item -> {
                PortTemplateTypeStatisticalDTO value = dozerBeanMapper.map(item, PortTemplateTypeStatisticalDTO.class);
                Template template = templateMapper.selectById(item.getTemplateId());
                value.setName(template.getName());
                value.setProductType(template.getProductType());
                value.setStatus(template.getStatus());
                value.setGmtCreate(generalService.localDateTime2Date(item.getGmtCreate()));
                value.setGmtModified(generalService.localDateTime2Date(item.getGmtModified()));

                // 渠道：C01-小贷，C02-保理，C03-青港易付，C04-财务信贷平台，C05-中台内管
                value.setSmallLoansNewAgreementCount(c01AgreementTypeCount);
                value.setSmallLoansNewContractCount(c01ContractTypeCount);
                value.setSmallLoansNewArchiveCount(c01ArchiveTypeCount);
                value.setEasyPayNewAgreementCount(c03AgreementTypeCount);
                value.setEasyPayNewContractCount(c03ContractTypeCount);
                value.setEasyPayNewArchiveCount(c03ArchiveTypeCount);
                value.setFactoringNewAgreementCount(c02AgreementTypeCount);
                value.setFactoringNewContractCount(c02ContractTypeCount);
                value.setFactoringNewArchiveCount(c02ArchiveTypeCount);
                portTemplateLogDtos.add(value);
            });
        }
        pagerInfo.setTotal(templateIPage.getTotal());

        return portTemplateLogDtos;
    }

    /**
     * 内管档案日志查询
     *
     * @param requestObj 内管档案日志查询
     * @return 内管使用的档案日志信息传输对象
     */
    public List<PortArchiveLogDTO> portArchiveLogQuery(PortArchiveLogQueryReq requestObj) {
        String channel = requestObj.getChannel();
        checkChannel(channel);
        PagerInfo pagerInfo = requestObj.getPagerInfo();
        Page<ArchiveOperationLog> archiveLogPage = new Page<>(pagerInfo.getPageNum(), pagerInfo.getPageSize());
        QueryWrapper<ArchiveOperationLog> queryWrapper = new QueryWrapper<>();
        String operationName = requestObj.getOperationName();
        String queryChannel = requestObj.getQueryChannel();
        String operationAccount = requestObj.getOperationAccount();

        String endDate = requestObj.getOperationEndDate();
        String begintDate = requestObj.getOperationStartDate();
        List<PortArchiveLogDTO> responseList = new ArrayList<>();

        if (StringUtils.isNotEmpty(queryChannel)) {
            queryWrapper.eq("channel", queryChannel);
        }

        if (StringUtils.isNotEmpty(operationName)) {
            queryWrapper.like("operator_name", operationName);
        }

        if (StringUtils.isNotEmpty(operationAccount)) {
            queryWrapper.like("operator_account", operationAccount);
        }

        if (StringUtils.isNotEmpty(begintDate) && StringUtils.isNotEmpty(endDate)) {
            // 创建时间
            queryWrapper.between("gmt_create", begintDate + " 00:00:00", endDate + " 23:59:59");
        } else {
            if (StringUtils.isNotEmpty(begintDate)) {
                queryWrapper.ge("gmt_create", begintDate + " 00:00:00");
            } else if (StringUtils.isNotEmpty(endDate)) {
                queryWrapper.le("gmt_create", endDate + " 23:59:59");
            }
        }

        queryWrapper.orderByDesc("gmt_create");

        // 查询
        IPage<ArchiveOperationLog> archiveOperationLogIPage =
            archiveOperationLogMapper.selectPage(archiveLogPage, queryWrapper);

        List<ArchiveOperationLog> records = archiveOperationLogIPage.getRecords();
        if (records != null) {
            records.forEach(value -> {
                PortArchiveLogDTO item = dozerBeanMapper.map(value, PortArchiveLogDTO.class);
                responseList.add(item);
            });
        }
        pagerInfo.setTotal(archiveOperationLogIPage.getTotal());
        return responseList;
    }

    /**
     * 内管档案查询
     *
     * @param requestObj 内管档案查询
     * @return 内管档案详情信息传输对象
     */
    public List<PortArchiveDto> portArchiveQuery(PortArchiveQueryReq requestObj) {
        String channel = requestObj.getChannel();
        checkChannel(channel);
        PagerInfo pagerInfo = requestObj.getPagerInfo();
        Page<Archive> archivePage = new Page<>(pagerInfo.getPageNum(), pagerInfo.getPageSize());
        QueryWrapper<Archive> queryWrapper = new QueryWrapper<>();
        String queryChannel = requestObj.getQueryChannel();

        List<PortArchiveDto> responseList = new ArrayList<>();

        String busId = requestObj.getBusId();
        String createBeginDate = requestObj.getCreateBeginDate();
        String createEndDate = requestObj.getCreateEndDate();
        String name = requestObj.getName();
        String productType = requestObj.getProductType();

        String gmtModifiedBeginDate = requestObj.getGmtModifiedBeginDate();
        String gmtModifiedEndDate = requestObj.getGmtModifiedEndDate();
        String gmtSubmissionBeginDate = requestObj.getGmtSubmissionBeginDate();
        String gmtSubmissionEndDate = requestObj.getGmtSubmissionEndDate();

        queryWrapper.eq("is_deleted", "0");
        if (StringUtils.isNotEmpty(createBeginDate) && StringUtils.isNotEmpty(createEndDate)) {
            // 创建时间
            queryWrapper.between("gmt_create", createBeginDate + " 00:00:00", createEndDate + " 23:59:59");
        } else {
            if (StringUtils.isNotEmpty(createBeginDate)) {
                queryWrapper.ge("gmt_create", createBeginDate + " 00:00:00");
            } else if (StringUtils.isNotEmpty(createEndDate)) {
                queryWrapper.le("gmt_create", createEndDate + " 23:59:59");
            }
        }

        if (StringUtils.isNotEmpty(gmtModifiedBeginDate) && StringUtils.isNotEmpty(gmtModifiedEndDate)) {
            // 修改时间
            queryWrapper.between("gmt_modified", gmtModifiedBeginDate + " 00:00:00", gmtModifiedEndDate + " 23:59:59");
        } else {
            if (StringUtils.isNotEmpty(gmtModifiedBeginDate)) {
                queryWrapper.ge("gmt_modified", gmtModifiedBeginDate + " 00:00:00");
            } else if (StringUtils.isNotEmpty(gmtModifiedEndDate)) {
                queryWrapper.le("gmt_modified", gmtModifiedEndDate + " 23:59:59");
            }
        }

        if (StringUtils.isNotEmpty(gmtSubmissionBeginDate) && StringUtils.isNotEmpty(gmtSubmissionEndDate)) {
            // 提交时间
            queryWrapper.between("gmt_submission", gmtSubmissionBeginDate + " 00:00:00",
                gmtSubmissionEndDate + " 23:59:59");
        } else {
            if (StringUtils.isNotEmpty(gmtSubmissionBeginDate)) {
                queryWrapper.ge("gmt_submission", gmtSubmissionBeginDate + " 00:00:00");
            } else if (StringUtils.isNotEmpty(gmtSubmissionEndDate)) {
                queryWrapper.le("gmt_submission", gmtSubmissionEndDate + " 23:59:59");
            }
        }

        if (StringUtils.isNotEmpty(name)) {
            queryWrapper.like("name", name);
        }

        if (StringUtils.isNotEmpty(busId)) {
            queryWrapper.eq("bus_id", busId);
        }

        if (StringUtils.isNotEmpty(productType)) {
            queryWrapper.like("product_type", productType);
        }

        if (StringUtils.isNotEmpty(queryChannel)) {
            queryWrapper.eq("channel", queryChannel);
        }

        queryWrapper.orderByDesc("gmt_create");

        // 查询
        IPage<Archive> iPage = archiveMapper.selectPage(archivePage, queryWrapper);

        List<Archive> records = archivePage.getRecords();
        if (records != null) {
            records.forEach(value -> {
                PortArchiveDto item = dozerBeanMapper.map(value, PortArchiveDto.class);
                if (value.getGmtCreate() != null) {
                    item.setGmtCreate(generalService.localDateTime2Date(value.getGmtCreate()));
                }

                if (value.getGmtModified() != null) {
                    item.setGmtModified(generalService.localDateTime2Date(value.getGmtModified()));
                }

                if (value.getGmtSubmission() != null) {
                    item.setGmtSubmission(generalService.localDateTime2Date(value.getGmtSubmission()));
                }
                if (value.getUrl() != null) {
                    item.setUrl(commUtils.getOssFullUrl(item.getUrl()));
                }
                responseList.add(item);
            });
        }
        pagerInfo.setTotal(iPage.getTotal());
        return responseList;
    }

    /**
     * 内管合约查询
     *
     * @param requestObject 内管合约查询请求
     * @return 内管合约详情信息传输对象
     */
    public List<PortContractDto> portQueryContract(PortQueryContractReq requestObject) {
        String channel = requestObject.getChannel();
        checkChannel(channel);
        PagerInfo pagerInfo = requestObject.getPagerInfo();
        Page<Contract> contractPage = new Page<>(pagerInfo.getPageNum(), pagerInfo.getPageSize());
        QueryWrapper<Contract> queryWrapper = new QueryWrapper<>();
        List<PortContractDto> responseList = new ArrayList<>();

        String appProcessNo = requestObject.getAppProcessNo();
        String busId = requestObject.getBusId();
        String contractName = requestObject.getContractName();
        String contractNo = requestObject.getContractNo();
        String contractTypeCode = requestObject.getContractTypeCode();
        Integer customerManager = requestObject.getCustomerManager();
        String queryChannel = requestObject.getQueryChannel();
        String productType = requestObject.getProductType();
        String status = requestObject.getStatus();
        String signatoryName = requestObject.getSignatoryName();
        String tsignatoryDateEnd = requestObject.getTsignatoryDateEnd();
        String tsignatoryDateStart = requestObject.getTsignatoryDateStart();

        queryWrapper.eq("is_deleted", "0");

        if (StringUtils.isNotEmpty(appProcessNo)) {
            queryWrapper.like("app_process_no", appProcessNo);
        }

        if (StringUtils.isNotEmpty(signatoryName)) {
            queryWrapper.like("signatory_name", signatoryName);
        }

        if (customerManager != null) {
            queryWrapper.eq("customer_manager", customerManager);
        }

        if (StringUtils.isNotEmpty(contractNo)) {
            queryWrapper.like("contract_no", contractNo);
        }

        if (StringUtils.isNotEmpty(contractName)) {
            queryWrapper.like("contract_name", contractName);
        }

        if (StringUtils.isNotEmpty(busId)) {
            queryWrapper.eq("bus_id", busId);
        }

        if (StringUtils.isNotEmpty(status)) {
            queryWrapper.eq("status", status);
        }

        if (StringUtils.isNotEmpty(queryChannel)) {
            queryWrapper.eq("channel", queryChannel);
        }

        if (StringUtils.isNotEmpty(productType)) {
            queryWrapper.like("product_type", productType);
        }

        if (StringUtils.isNotEmpty(contractTypeCode)) {
            queryWrapper.eq("contract_type_code", contractTypeCode);
        }

        if (StringUtils.isNotEmpty(tsignatoryDateEnd) && StringUtils.isNotEmpty(tsignatoryDateStart)) {
            // 创建时间
            queryWrapper.between("tsignatory_date", tsignatoryDateStart + " 00:00:00", tsignatoryDateEnd + " 23:59:59");
        } else {
            if (StringUtils.isNotEmpty(tsignatoryDateStart)) {
                queryWrapper.ge("tsignatory_date", tsignatoryDateStart + " 00:00:00");
            } else if (StringUtils.isNotEmpty(tsignatoryDateEnd)) {
                queryWrapper.le("tsignatory_date", tsignatoryDateEnd + " 23:59:59");
            }
        }

        queryWrapper.orderByDesc("gmt_create");

        // 查询
        IPage<Contract> iPage = contractMapper.selectPage(contractPage, queryWrapper);

        List<Contract> records = iPage.getRecords();
        if (records != null) {
            records.forEach(item -> {
                PortContractDto value = dozerBeanMapper.map(item, PortContractDto.class);
                if (item.getCustomerManager() != null) {
                    // TODO: [查询用户信息] 负责人：刘林晓，事项：内管根据用户 id 查询用户名称时，暂时无法传入企业编号，所以存在多个信息默认会取第一个
                    // 调整方向：根据 userId 和 enterpriseId 查询用户才正确，由于当前方法是被应用在内管统计查询，临时无法调整
                    // 添加时间：2020-12-08 预计处理时间：待定
                    UserInfoDto userInfo = userCenterModel.getUserInfo(item.getCustomerManager(), item.getChannel(),
                        item.getCustomerManager(), null);
                    if (userInfo != null) {
                        value.setCustomerManager(userInfo.getUserBaseInformationDto().getUserName());
                    }
                }
                value.setGmtCreate(generalService.localDateTime2Date(item.getGmtCreate()));
                value.setGmtModified(generalService.localDateTime2Date(item.getGmtModified()));
                if (item.getTsignatoryDate() != null) {
                    value.setTsignatoryDate(generalService.localDateTime2Date(item.getTsignatoryDate()));
                }

                QueryWrapper<ContractType> contractTypeQueryWrapper = new QueryWrapper<>();
                contractTypeQueryWrapper.eq("channel", item.getChannel());
                contractTypeQueryWrapper.eq("code", item.getContractTypeCode());
                List<ContractType> contractTypes = contractTypeMapper.selectList(contractTypeQueryWrapper);
                if (contractTypes != null && contractTypes.size() > 0) {
                    ContractType contractType = contractTypes.get(0);
                    value.setContractTypeCode(contractType.getName());
                } else {
                    value.setContractTypeCode("");
                }
                responseList.add(value);
            });
        }
        pagerInfo.setTotal(iPage.getTotal());
        return responseList;
    }

    /**
     * 合约签署信息统计
     *
     * @param requestObj 合约签署信息统计请求对象
     * @return 内管合约统计查询传输对象
     */
    public List<PortContractSignStatisticsDto> portContractStatistics(PortContractSignStatisticsReq requestObject) {
        String channel = requestObject.getChannel();
        checkChannel(channel);
        PagerInfo pagerInfo = requestObject.getPagerInfo();
        Page<Contract> contractPage = new Page<>(pagerInfo.getPageNum(), pagerInfo.getPageSize());
        QueryWrapper<Contract> queryWrapper = new QueryWrapper<>();
        List<PortContractSignStatisticsDto> responseList = new ArrayList<>();

        List<ContractSignStatistics> contractSignStatisticsList = this.contractMapper.statistics(requestObject.getCreateTimeStart(), requestObject.getCreateTimeEnd());

        String status = requestObject.getStatus();
        String queryChannel = requestObject.getQueryChannel();
        String productType = requestObject.getProductType();
        String contractTypeCode = requestObject.getContractTypeCode();
        Date createTimeStart = requestObject.getCreateTimeStart();
        Date createTimeEnd = requestObject.getCreateTimeEnd();

        if (StringUtils.isNotEmpty(status)) {
            queryWrapper.eq("status", status);
        }

        if (StringUtils.isNotEmpty(queryChannel)) {
            queryWrapper.eq("channel", queryChannel);
        }

        if (StringUtils.isNotEmpty(productType)) {
            queryWrapper.like("product_type", productType);
        }
        if (StringUtils.isNotEmpty(contractTypeCode)) {
            queryWrapper.eq("contract_type_code", contractTypeCode);
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (null != createTimeStart && null != createTimeEnd) {
            queryWrapper.between("gmt_create", simpleDateFormat.format(createTimeStart) + " 00:00:00",
                simpleDateFormat.format(createTimeEnd) + " 23:59:59");
        } else {
            if (createTimeStart != null) {
                queryWrapper.ge("gmt_create", simpleDateFormat.format(createTimeStart) + " 00:00:00");
            } else {
                if (createTimeEnd != null) {
                    queryWrapper.le("gmt_create", simpleDateFormat.format(createTimeEnd) + " 23:59:59");
                }
            }
        }
        queryWrapper.orderByDesc("gmt_create");
        // 查询
        IPage<Contract> iPage = contractMapper.selectPage(contractPage, queryWrapper);

        List<Contract> records = iPage.getRecords();
        if (null != records) {
            records.forEach(item -> {
                PortContractSignStatisticsDto value = dozerBeanMapper.map(item, PortContractSignStatisticsDto.class);
                value.setGmtCreate(generalService.localDateTime2Date(item.getGmtCreate()));
                contractSignStatisticsList.forEach(x -> {
                    if (x != null && "C01".equals(x.getChannel())) {
                        value.setSmallLoan(dozerBeanMapper.map(x, PortContractDetailDto.class));
                    }
                    if (x != null && "C02".equals(x.getChannel())) {
                        value.setFactoring(dozerBeanMapper.map(x, PortContractDetailDto.class));
                    }
                    if (x != null && "C03".equals(x.getChannel())) {
                        value.setEasyPay(dozerBeanMapper.map(x, PortContractDetailDto.class));
                    }
                });

                responseList.add(value);
            });
        }
        pagerInfo.setTotal(iPage.getTotal());
        return responseList;
    }

    /**
     * 校验渠道
     *
     * @param channel 渠道
     */
    public void checkChannel(String channel) {
        if (!SystemConsts.CHANNEL_INTERNAL_MANAGEMENT.equals(channel)) {
            throw new BusinessException("非中台内管不能调用", "ECCT0718");
        }
    }

    /**
     * 内管合约日志查询
     *
     * @param requestObj 内管合约日志查询
     * @return 内管使用的合约日志传输对象
     */
    public List<PortContractLogDTO> portContractLog(PortContractLogQueryReq requestObj) {

        // 参数
        QueryWrapper<ServiceRecord> queryWrapper = new QueryWrapper<>();
        String channel = requestObj.getChannel();
        PagerInfo pagerInfo = requestObj.getPagerInfo();
        Page<ServiceRecord> serviceRecordPage = new Page<>(pagerInfo.getPageNum(), pagerInfo.getPageSize());
        List<PortContractLogDTO> responseList = new ArrayList<>();

        String callOwner = requestObj.getCallOwner();
        String callServer = requestObj.getCallServer();
        String callState = requestObj.getCallState();
        String operationAccount = requestObj.getOperationAccount();
        String operationName = requestObj.getOperationName();
        String queryChannel = requestObj.getQueryChannel();
        String operationStartDate = requestObj.getOperationStartDate();
        String operationEndDate = requestObj.getOperationEndDate();

        if (StringUtils.isNotEmpty(callOwner)) {
            queryWrapper.eq("service_provider", callOwner);
        }

        if (StringUtils.isNotEmpty(callServer)) {
            queryWrapper.like("service_name", callServer);
        }
        if (StringUtils.isNotEmpty(callState)) {
            queryWrapper.eq("service_status", callState);
        }
        if (StringUtils.isNotEmpty(operationAccount)) {
            queryWrapper.eq("operator_account", operationAccount);
        }

        if (StringUtils.isNotEmpty(operationName)) {
            queryWrapper.like("operator_name", operationName);
        }
        if (StringUtils.isNotEmpty(queryChannel)) {
            queryWrapper.eq("channel", queryChannel);
        }
        if (StringUtils.isNotEmpty(operationStartDate) && StringUtils.isNotEmpty(operationEndDate)) {
            // 创建时间
            queryWrapper.between("gmt_create", operationStartDate + " 00:00:00", operationEndDate + " 23:59:59");
        } else {
            if (StringUtils.isNotEmpty(operationStartDate)) {
                queryWrapper.ge("gmt_create", operationStartDate + " 00:00:00");
            } else if (StringUtils.isNotEmpty(operationEndDate)) {
                queryWrapper.le("gmt_create", operationEndDate + " 23:59:59");
            }
        }

        queryWrapper.orderByDesc("gmt_create");

        // 查询
        IPage<ServiceRecord> iPage = serviceRecordMapper.selectPage(serviceRecordPage, queryWrapper);

        List<ServiceRecord> records = serviceRecordPage.getRecords();
        if (records != null) {
            records.forEach(value -> {
                PortContractLogDTO item = dozerBeanMapper.map(value, PortContractLogDTO.class);
                Contract contract = contractMapper.selectById(value.getContractId());
                if (contract != null) {
                    item.setContractName(contract.getContractName());
                }
                item.setGmtCreate(generalService.localDateTime2Date(value.getGmtCreate()));
                item.setResponseMsg("--");
                if ("时间戳".equals(value.getServiceName()) || "文本签".equals(value.getServiceName())) {
                    item.setResponseMsg(value.getResponseMsg());
                }
                responseList.add(item);
            });
        }
        pagerInfo.setTotal(iPage.getTotal());
        return responseList;
    }

    /**
     * 关联合约查询请求
     *
     * @param requestObj 关联合约查询请求
     * @return 内管合约详情信息传输对象
     */
    public List<PortContractDto> queryRelationContract(PortQueryRelationContractReq requestObj) {
        List<Contract> contracts = this.contractMapper.queryRelationContract(requestObj.getContractId());
        List<PortContractDto> contractDtos = new ArrayList<>();
        if (contracts != null) {
            contracts.forEach(contract -> {
                PortContractDto contractDto = dozerBeanMapper.map(contract, PortContractDto.class);
                if (contract.getTsignatoryDate() != null) {
                    contractDto.setTsignatoryDate(generalService.localDateTime2Date(contract.getTsignatoryDate()));
                }
                if (contractDto.getOssUrl() != null) {
                    contractDto.setOssUrl(commUtils.getOssFullUrl(contractDto.getOssUrl()));
                }
                if (contractDto.getPdfOssUrl() != null) {
                    contractDto.setPdfOssUrl(commUtils.getOssFullUrl(contractDto.getPdfOssUrl()));
                }
                contractDtos.add(contractDto);
            });
        }
        return contractDtos;
    }

    /**
     * 合约类型表dao
     */
    @Autowired
    ContractTypeMapper contractTypeMapper;

    /**
     * 获取合约类型code
     *
     * @param template 合同模板表
     * @return 合约类型code
     */
    public String getContractTypeCode(Template template) {
        if (template.getContractTypeId() != null) {
            ContractType contractType = contractTypeMapper.selectById(template.getContractTypeId());
            if (contractType != null) {
                return contractType.getCode();
            }
        }
        return "";
    }

    /**
     * 获取合约类型
     *
     * @return 合约类型信息传输对象
     */
    public List<ContractTypeDTO> getContractType() {
        List<ContractTypeDTO> list = new ArrayList<>();
        QueryWrapper queryWrapper = new QueryWrapper();
        list = contractTypeMapper.selectList(queryWrapper);
        return list;
    }

    /**
     * 内管模版日志导出查询
     *
     * @param requestObj 内管模版日志导出查询
     * @return 提供给内管使用的模板日志传输对象
     */
    public List<PortTemplateLogDTO> portTemplateLogExport(PortTemplateLogQueryExportReq requestObj) {
        String channel = requestObj.getChannel();
        checkChannel(channel);
        QueryWrapper<TemplateOperationLog> queryWrapper = new QueryWrapper<>();
        String operationName = requestObj.getOperationName();
        String queryChannel = requestObj.getQueryChannel();
        String operationType = requestObj.getOperationType();
        String operationAccount = requestObj.getOperationAccount();
        String endDate = requestObj.getOperationEndDate();
        String begintDate = requestObj.getOperationStartDate();
        List<PortTemplateLogDTO> responseList = new ArrayList<>();

        if (StringUtils.isNotEmpty(queryChannel)) {
            queryWrapper.eq("channel", queryChannel);
        }

        if (StringUtils.isNotEmpty(operationName)) {
            queryWrapper.like("operator_name", operationName);
        }

        if (StringUtils.isNotEmpty(operationAccount)) {
            queryWrapper.like("operator_account", operationAccount);
        }

        if (StringUtils.isNotEmpty(operationType)) {
            queryWrapper.eq("operation_type", operationType);
        }

        if (StringUtils.isNotEmpty(begintDate) && StringUtils.isNotEmpty(endDate)) {
            // 创建时间
            queryWrapper.between("gmt_create", begintDate + " 00:00:00", endDate + " 23:59:59");
        } else {
            if (StringUtils.isNotEmpty(begintDate)) {
                queryWrapper.ge("gmt_create", begintDate + " 00:00:00");
            } else if (StringUtils.isNotEmpty(endDate)) {
                queryWrapper.le("gmt_create", endDate + " 23:59:59");
            }
        }

        queryWrapper.orderByDesc("gmt_create");

        // 查询
        List<TemplateOperationLog> records = templateOperationLogMapper.selectList(queryWrapper);
        if (records != null) {
            records.forEach(value -> {
                PortTemplateLogDTO item = dozerBeanMapper.map(value, PortTemplateLogDTO.class);
                item.setGmtCreate(generalService.localDateTime2Date(value.getGmtCreate()));
                item.setGmtModified(generalService.localDateTime2Date(value.getGmtModified()));
                responseList.add(item);
            });
        }
        return responseList;
    }

    /**
     * 内管合约日志导出查询
     *
     * @param requestObj 内管合约日志导出查询
     * @return 内管使用的合约日志传输对象
     */
    public List<PortContractLogDTO> portContractLogExport(PortContractLogQueryExportReq requestObj) {

        // 参数
        QueryWrapper<ServiceRecord> queryWrapper = new QueryWrapper<>();
        String channel = requestObj.getChannel();
        List<PortContractLogDTO> responseList = new ArrayList<>();

        String callOwner = requestObj.getCallOwner();
        String callServer = requestObj.getCallServer();
        String callState = requestObj.getCallState();
        String operationAccount = requestObj.getOperationAccount();
        String operationName = requestObj.getOperationName();
        String queryChannel = requestObj.getQueryChannel();
        String operationStartDate = requestObj.getOperationStartDate();
        String operationEndDate = requestObj.getOperationEndDate();

        if (StringUtils.isNotEmpty(callOwner)) {
            queryWrapper.eq("service_provider", callOwner);
        }

        if (StringUtils.isNotEmpty(callServer)) {
            queryWrapper.like("service_name", callServer);
        }
        if (StringUtils.isNotEmpty(callState)) {
            queryWrapper.eq("service_status", callState);
        }
        if (StringUtils.isNotEmpty(operationAccount)) {
            queryWrapper.eq("operator_account", operationAccount);
        }

        if (StringUtils.isNotEmpty(operationName)) {
            queryWrapper.like("operator_name", operationName);
        }
        if (StringUtils.isNotEmpty(queryChannel)) {
            queryWrapper.eq("channel", queryChannel);
        }
        if (StringUtils.isNotEmpty(operationStartDate) && StringUtils.isNotEmpty(operationEndDate)) {
            // 创建时间
            queryWrapper.between("gmt_create", operationStartDate + " 00:00:00", operationEndDate + " 23:59:59");
        } else {
            if (StringUtils.isNotEmpty(operationStartDate)) {
                queryWrapper.ge("gmt_create", operationStartDate + " 00:00:00");
            } else if (StringUtils.isNotEmpty(operationEndDate)) {
                queryWrapper.le("gmt_create", operationEndDate + " 23:59:59");
            }
        }
        queryWrapper.orderByDesc("gmt_create");

        List<ServiceRecord> records = serviceRecordMapper.selectList(queryWrapper);
        if (records != null) {
            records.forEach(value -> {
                PortContractLogDTO item = dozerBeanMapper.map(value, PortContractLogDTO.class);
                Contract contract = contractMapper.selectById(value.getContractId());
                item.setContractName(contract.getContractName());
                item.setGmtCreate(generalService.localDateTime2Date(value.getGmtCreate()));
                responseList.add(item);
            });
        }
        return responseList;
    }

    /**
     * 档案日志导出查询
     *
     * @param requestObj 档案日志导出查询
     * @return 内管使用的档案日志信息传输对象
     */
    public List<PortArchiveLogDTO> portArchiveLogQueryExport(PortArchiveLogQueryExportReq requestObj) {
        String channel = requestObj.getChannel();
        checkChannel(channel);
        QueryWrapper<ArchiveOperationLog> queryWrapper = new QueryWrapper<>();
        String operationName = requestObj.getOperationName();
        String queryChannel = requestObj.getQueryChannel();
        String operationAccount = requestObj.getOperationAccount();

        String endDate = requestObj.getOperationEndDate();
        String begintDate = requestObj.getOperationStartDate();
        List<PortArchiveLogDTO> responseList = new ArrayList<>();

        if (StringUtils.isNotEmpty(queryChannel)) {
            queryWrapper.eq("channel", queryChannel);
        }

        if (StringUtils.isNotEmpty(operationName)) {
            queryWrapper.like("operator_name", operationName);
        }

        if (StringUtils.isNotEmpty(operationAccount)) {
            queryWrapper.like("operator_account", operationAccount);
        }

        if (StringUtils.isNotEmpty(begintDate) && StringUtils.isNotEmpty(endDate)) {
            // 创建时间
            queryWrapper.between("gmt_create", begintDate + " 00:00:00", endDate + " 23:59:59");
        } else {
            if (StringUtils.isNotEmpty(begintDate)) {
                queryWrapper.ge("gmt_create", begintDate + " 00:00:00");
            } else if (StringUtils.isNotEmpty(endDate)) {
                queryWrapper.le("gmt_create", endDate + " 23:59:59");
            }
        }

        queryWrapper.orderByDesc("gmt_create");

        // 查询
        List<ArchiveOperationLog> records = archiveOperationLogMapper.selectList(queryWrapper);
        if (records != null) {
            records.forEach(value -> {
                PortArchiveLogDTO item = dozerBeanMapper.map(value, PortArchiveLogDTO.class);
                responseList.add(item);
            });
        }
        return responseList;
    }
}
